package com.insight.modules.system.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuanqiao.insight.common.constant.CommonConstant;
import com.yuanqiao.insight.common.util.common.LocalCacheUtils;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import com.insight.common.api.vo.Result;
import com.insight.common.aspect.annotation.AutoLog;
import com.insight.common.constant.CacheConstant;
import com.insight.common.system.query.QueryGenerator;
import com.insight.common.system.vo.DictModel;
import com.insight.common.system.vo.DictQuery;
import com.insight.common.util.FieldPresenceUtil;
import com.insight.common.util.ImportExcelUtil;
import com.insight.common.util.SqlInjectionUtil;
import com.insight.common.util.oConvertUtils;
import com.yuanqiao.insight.acore.system.entity.SysDict;
import com.yuanqiao.insight.acore.system.entity.SysDictItem;
import com.insight.modules.system.model.SysDictTree;
import com.yuanqiao.insight.acore.system.vo.TreeSelectModel;
import com.yuanqiao.insight.acore.system.service.ISysDictItemService;
import com.yuanqiao.insight.acore.system.service.ISysDictService;
import com.insight.modules.system.util.ExcelUtil;
import com.yuanqiao.insight.acore.system.vo.SysArea;
import com.yuanqiao.insight.acore.system.vo.SysAreaTreeModel;
import com.insight.modules.system.vo.SysDictPage;
import com.insight.modules.umpPwdManage.entity.UmpPwdManage;
import com.insight.modules.umpPwdManage.service.IUmpPwdManageService;
import com.insight.modules.util.ZipEncryUtils;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * <p>
 * 字典表 前端控制器
 * </p>
 *
 * @Author zhangweijian
 * @since 2018-12-28
 */
@RestController
@RequestMapping("/sys/dict")
@Slf4j
public class SysDictController {

	@Autowired
	private ISysDictService sysDictService;
	@Autowired
	private ISysDictItemService sysDictItemService;
	@Autowired
	private RedisTemplate<String, Object> redisTemplate;
	@Autowired
	private IUmpPwdManageService umpPwdManageService;
	@Autowired
	private ZipEncryUtils zipEncryUtils;

	LocalCacheUtils cacheUtils = LocalCacheUtils.getInstance();
//    @Value("${sysArea}")
    private String sysArea;
	@Value("${excel.dictTemplate}")
	private String path;


    @AutoLog(value = "数据字典-列表展示")
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public Result<IPage<SysDict>> queryPageList(SysDict sysDict,@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,HttpServletRequest req) {
		Result<IPage<SysDict>> result = new Result<IPage<SysDict>>();
		String dictName = sysDict.getDictName();
		String dictCode = sysDict.getDictCode();
		String description = sysDict.getDescription();
		if (StringUtils.isNotBlank(dictName)){
			sysDict.setDictName(null);
		}
		if (StringUtils.isNotBlank(dictCode)){
			sysDict.setDictCode(null);
		}
		if (StringUtils.isNotBlank(description)){
			sysDict.setDescription(null);
		}
		QueryWrapper<SysDict> queryWrapper = QueryGenerator.initQueryWrapper(sysDict, req.getParameterMap());
		if (StringUtils.isNotBlank(dictName)){
			queryWrapper.like("dict_name",dictName);
		}
		if (StringUtils.isNotBlank(dictCode)){
			queryWrapper.like("dict_code",dictCode);
		}
		if (StringUtils.isNotBlank(description)){
			queryWrapper.like("description",description);
		}
		Page<SysDict> page = new Page<SysDict>(pageNo, pageSize);
		IPage<SysDict> pageList = sysDictService.page(page, queryWrapper);
		log.debug("查询当前页："+pageList.getCurrent());
		log.debug("查询当前页数量："+pageList.getSize());
		log.debug("查询结果数量："+pageList.getRecords().size());
		log.debug("数据总数："+pageList.getTotal());
		result.setSuccess(true);
		result.setResult(pageList);
		return result;
	}

    /**
     * 获取字典数
     * @param dictCode
     * @return
     */
    @RequestMapping(value = "/getDictCodeChild", method = RequestMethod.GET)
    public Result<?> getDictCodeChild(String dictCode){
        List<DictModel> dictModels = sysDictService.queryDictItemsByCode(dictCode);
        List<Map<String,String>> resultList = new ArrayList<>(dictModels.size());
        for (DictModel dictModel:dictModels) {
            Map<String,String> map = new HashMap(2);
            map.put("id",dictModel.getValue());
            map.put("label",dictModel.getText());
            resultList.add(map);

        }
	    return Result.OK(resultList);
    }
	/**
	 * @功能：获取树形字典数据
	 * @param sysDict
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/treeList", method = RequestMethod.GET)
	public Result<List<SysDictTree>> treeList(SysDict sysDict,@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,HttpServletRequest req) {
		Result<List<SysDictTree>> result = new Result<>();
		LambdaQueryWrapper<SysDict> query = new LambdaQueryWrapper<>();
		// 构造查询条件
		String dictName = sysDict.getDictName();
		if(oConvertUtils.isNotEmpty(dictName)) {
			query.like(true, SysDict::getDictName, dictName);
		}
		query.orderByDesc(true, SysDict::getCreateTime);
		List<SysDict> list = sysDictService.list(query);
		List<SysDictTree> treeList = new ArrayList<>();
		for (SysDict node : list) {
			treeList.add(new SysDictTree(node));
		}
		result.setSuccess(true);
		result.setResult(treeList);
		return result;
	}




	@RequestMapping(value = "/getDictItem/{dictCode}", method = RequestMethod.GET)
	public Result<?> getDictItem(@PathVariable String dictCode) {
		log.info(" dictCode : "+ dictCode);
		QueryWrapper<SysDict> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("dict_code",dictCode);
		SysDict dict = sysDictService.getOne(queryWrapper);
		List<SysDictItem> sysDictItems = sysDictItemService.selectItemsByMainId(dict.getId());
		ArrayList<Map<Object, Object>> maps = new ArrayList<>();
		for (SysDictItem sysDictItem : sysDictItems) {
			Map<Object, Object> map = new HashMap<>();
			map.put("text",sysDictItem.getItemText());//显示的值
			map.put("value",sysDictItem.getItemValue());//存的值
			maps.add(map);
		}
		return Result.OK(maps);
	}
	/**
	 * 获取全部字典数据
	 *
	 * @return
	 */
	@RequestMapping(value = "/queryAllDictItems", method = RequestMethod.GET)
	public Result<?> queryAllDictItems(HttpServletRequest request) {
		Map<String, List<DictModel>> res = new HashMap<String, List<DictModel>>();
		res = sysDictService.queryAllDictItems();
		return Result.ok(res);
	}

	/**
	 * 获取字典数据
	 * @param dictCode
	 * @return
	 */
	@RequestMapping(value = "/getDictText/{dictCode}/{key}", method = RequestMethod.GET)
	public Result<String> getDictText(@PathVariable("dictCode") String dictCode, @PathVariable("key") String key) {
		log.info(" dictCode : "+ dictCode);
		Result<String> result = new Result<String>();
		String text = null;
		try {
			if (dictCode == null || key == null || sysDictService == null) {
				result.setSuccess(false);
				result.setResult(text);
				return result;
			}
			text = sysDictService.queryDictTextByKey(dictCode, key);
			result.setSuccess(true);
			result.setResult(text);
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			result.error500("操作失败");
			return result;
		}
		return result;
	}

	/**
	 * 大数据量的字典表 走异步加载  即前端输入内容过滤数据
	 * @param dictCode
	 * @return
	 */
	@RequestMapping(value = "/loadDict/{dictCode}", method = RequestMethod.GET)
	public Result<List<DictModel>> loadDict(@PathVariable String dictCode,@RequestParam(name="keyword") String keyword, @RequestParam(value = "sign",required = false) String sign,HttpServletRequest request) {
		log.info(" 加载字典表数据,加载关键字: "+ keyword);
		Result<List<DictModel>> result = new Result<List<DictModel>>();
		List<DictModel> ls = null;
		try {
			if (dictCode == null || sysDictService == null) {
				result.error500("字典Code为空或服务不可用");
				return result;
			}
			if(dictCode.indexOf(',')!=-1) {
				String[] params = dictCode.split(",");
				if(params.length!=3) {
					result.error500("字典Code格式不正确！");
					return result;
				}
				ls = sysDictService.queryTableDictItems(params[0],params[1],params[2],keyword);
				result.setSuccess(true);
				result.setResult(ls);
				log.info(result.toString());
			}else {
				result.error500("字典Code格式不正确！");
			}
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			result.error500("操作失败");
			return result;
		}
		return result;
	}

	/**
	 * 根据字典code加载字典text 返回
	 */
	@RequestMapping(value = "/loadDictItem/{dictCode}", method = RequestMethod.GET)
	public Result<List<String>> loadDictItem(@PathVariable String dictCode,@RequestParam(name="key") String keys, @RequestParam(value = "sign",required = false) String sign,HttpServletRequest request) {
		Result<List<String>> result = new Result<>();
		try {
			if (dictCode == null || sysDictService == null) {
				result.error500("字典Code为空或服务不可用");
				return result;
			}
			if(dictCode.indexOf(',')!=-1) {
				String[] params = dictCode.split(",");
				if(params.length!=3) {
					result.error500("字典Code格式不正确！");
					return result;
				}
				List<String> texts = sysDictService.queryTableDictByKeys(params[0], params[1], params[2], keys);

				result.setSuccess(true);
				result.setResult(texts);
				log.info(result.toString());
			}else {
				result.error500("字典Code格式不正确！");
			}
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			result.error500("操作失败");
			return result;
		}

		return result;
	}

	/**
	 * 根据表名——显示字段-存储字段 pid 加载树形数据
	 */
	@SuppressWarnings("unchecked")
/*
	@RequestMapping(value = "/loadTreeData", method = RequestMethod.GET)
	public Result<List<TreeSelectModel>> loadTreeData(@RequestParam(name="pid") String pid,
												  @RequestParam(name="pidField") String pidField,
												  @RequestParam(name="tableName") String tbname,
												  @RequestParam(name="text") String text,
												  @RequestParam(name="code") String code,
												  @RequestParam(name="hasChildField") String hasChildField,
												  @RequestParam(name="condition") String condition,
												  @RequestParam(value = "sign",required = false) String sign,HttpServletRequest request) {

		Result<List<TreeSelectModel>> result = new Result<List<TreeSelectModel>>();
		Map<String, String> query = null;
		if(oConvertUtils.isNotEmpty(condition)) {
			query = JSON.parseObject(condition, Map.class);
		}
		// SQL注入漏洞 sign签名校验(表名,label字段,val字段,条件)
		String dictCode = tbname+","+text+","+code+","+condition;
        SqlInjectionUtil.filterContent(dictCode);
		List<TreeSelectModel> ls = sysDictService.queryTreeList(query,tbname, text, code, pidField, pid,hasChildField);
		result.setSuccess(true);
		result.setResult(ls);
		return result;
	}
*/


	@RequestMapping(value = "/loadTreeData", method = RequestMethod.GET)
	public Result<List<TreeSelectModel>> loadTreeData(@RequestParam(name="pid") String pid,
													  @RequestParam(name="pidField") String pidField,
													  @RequestParam(name="tableName") String tbname,
													  @RequestParam(name="text") String text,
													  @RequestParam(name="code") String code,
													  @RequestParam(name="hasChildField") String hasChildField,
													  @RequestParam(name="condition") String condition,
													  @RequestParam(value = "sign",required = false) String sign,HttpServletRequest request) {

		Result<List<TreeSelectModel>> result = new Result<List<TreeSelectModel>>();
		Map<String, Object> query = null;
		if(oConvertUtils.isNotEmpty(condition)) {
			query = JSON.parseObject(condition, Map.class);
		}
		// SQL注入漏洞 sign签名校验(表名,label字段,val字段,条件)
		String dictCode = tbname+","+text+","+code+","+condition;
		SqlInjectionUtil.filterContent(dictCode);
		List<TreeSelectModel> ls = sysDictService.queryTreeList(query,tbname, text, code, pidField, pid,hasChildField);
		for (TreeSelectModel treeSelectModel: ls ) {
			String parentId = treeSelectModel.getKey();
			//List<TreeSelectModel> children = sysDictService.findChildren(tbname, text, code, pidField, parentId);
			List<TreeSelectModel> children =sysDictService.queryTreeList(query,tbname, text, code, pidField, parentId,hasChildField);
			treeSelectModel.setChildren(children);
		}

		JSONArray array= JSONArray.parseArray(JSONObject.toJSONString(ls));
		remove (array);
		result.setSuccess(true);
		result.setResult(array);
		return result;
	}

	public void remove (JSONArray array){
		for (int j = 0; j <array.size() ; j++) {
			JSONObject jsonObject = array.getJSONObject(j);
			JSONArray children = array.getJSONObject(j).getJSONArray("children");
			if (children.size()==0){
				jsonObject.remove("children");
			}

		}
	}




	/**
	 * 【APP接口】根据字典配置查询表字典数据
	 * @param query
	 * @param pageNo
	 * @param pageSize
	 * @return
	 */
	@GetMapping("/queryTableData")
	public Result<List<DictModel>> queryTableData(DictQuery query,
												  @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
												  @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
												  @RequestParam(value = "sign",required = false) String sign,HttpServletRequest request){
		Result<List<DictModel>> res = new Result<List<DictModel>>();
		// SQL注入漏洞 sign签名校验
		String dictCode = query.getTable()+","+query.getText()+","+query.getCode();
        SqlInjectionUtil.filterContent(dictCode);
		List<DictModel> ls = this.sysDictService.queryDictTablePageList(query,pageSize,pageNo);
		res.setResult(ls);
		res.setSuccess(true);
		return res;
	}

	/**
	 * @功能：新增
	 * @param sysDict
	 * @return
	 */
	@AutoLog(value = "数据字典-添加")
	//@RequiresRoles({"admin"})
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public Result<SysDict> add(@RequestBody SysDict sysDict) {
		Result<SysDict> result = new Result<SysDict>();
		try {
			if (sysDict == null) {
				return result.error500("请求参数为空");
			}
			sysDict.setCreateTime(new Date());
			sysDict.setDelFlag(CommonConstant.DEL_FLAG_0);
			if (sysDictService != null) {
				sysDictService.save(sysDict);
			}
			result.success("保存成功！");
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			result.error500("操作失败");
		}
		return result;
	}

	/**
	 * @功能：编辑
	 * @param sysDict
	 * @return
	 */
	@AutoLog(value = "数据字典-编辑")
	//@RequiresRoles({"admin"})
	@RequestMapping(value = "/edit", method = RequestMethod.PUT)
	public Result<SysDict> edit(@RequestBody SysDict sysDict) {
		Result<SysDict> result = new Result<SysDict>();
		SysDict sysdict = sysDictService.getById(sysDict.getId());
		if(sysdict==null) {
			result.error500("未找到对应实体");
		}else {
			sysDict.setUpdateTime(new Date());
			boolean ok = sysDictService.updateById(sysDict);
			if(ok) {
				result.success("编辑成功!");
			}
		}
		return result;
	}

	/**
	 * @功能：删除
	 * @param id
	 * @return
	 */
	@AutoLog(value = "数据字典-删除")
	//@RequiresRoles({"admin"})
	@RequestMapping(value = "/delete", method = RequestMethod.DELETE)
	@CacheEvict(value={CacheConstant.SYS_DICT_CACHE,CacheConstant.SYSDICT_ITEM__CACHE}, allEntries=true)
	public Result<SysDict> delete(@RequestParam(name="id",required=true) String id) {
		Result<SysDict> result = new Result<SysDict>();
		boolean ok = sysDictService.removeById(id);
		if(ok) {
			result.success("删除成功!");
		}else{
			result.error500("删除失败!");
		}
		return result;
	}

	/**
	 * @功能：批量删除
	 * @param ids
	 * @return
	 */
	//@RequiresRoles({"admin"})
	@RequestMapping(value = "/deleteBatch", method = RequestMethod.DELETE)
	@CacheEvict(value={CacheConstant.SYS_DICT_CACHE,CacheConstant.SYSDICT_ITEM__CACHE}, allEntries=true)
	public Result<SysDict> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		Result<SysDict> result = new Result<SysDict>();
		if(oConvertUtils.isEmpty(ids)) {
			result.error500("参数不识别！");
		}else {
			sysDictService.removeByIds(Arrays.asList(ids.split(",")));
			result.success("删除成功!");
		}
		return result;
	}

	/**
	 * @功能：刷新缓存
	 * @return
	 */
	@AutoLog(value = "数据字典-刷新缓存")
	@RequestMapping(value = "/refleshCache")
	public Result<?> refleshCache() {
		Result<?> result = new Result<SysDict>();
		//清空字典缓存
		Set keys = redisTemplate.keys(CacheConstant.SYS_DICT_CACHE + "*");
		Set keys2 = redisTemplate.keys(CacheConstant.SYS_DICT_TABLE_CACHE + "*");
		Set keys3 = redisTemplate.keys(CacheConstant.SYS_DEPARTS_CACHE + "*");
		Set keys4 = redisTemplate.keys(CacheConstant.SYS_DEPART_IDS_CACHE + "*");
		Set keys5 = redisTemplate.keys(CacheConstant.SYSDICT_ITEM__CACHE + "*");
		redisTemplate.delete(keys);
		redisTemplate.delete(keys2);
		redisTemplate.delete(keys3);
		redisTemplate.delete(keys4);
		redisTemplate.delete(keys5);
		return result;
	}

	/**
	 * 导出excel
	 *
	 * @param request
	 */
//	public ModelAndView exportXls(SysDict sysDict,HttpServletRequest request) {
//		// Step.1 组装查询条件
//		QueryWrapper<SysDict> queryWrapper = QueryGenerator.initQueryWrapper(sysDict, request.getParameterMap());
//		//Step.2 AutoPoi 导出Excel
//		ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
//		List<SysDictPage> pageList = new ArrayList<SysDictPage>();
//
//		List<SysDict> sysDictList = sysDictService.list(queryWrapper);
//		for (SysDict dictMain : sysDictList) {
//			SysDictPage vo = new SysDictPage();
//			BeanUtils.copyProperties(dictMain, vo);
//			// 查询机票
//			List<SysDictItem> sysDictItemList = sysDictItemService.selectItemsByMainId(dictMain.getId());
//			vo.setSysDictItemList(sysDictItemList);
//			pageList.add(vo);
//		}
//
//		// 导出文件名称
//		mv.addObject(NormalExcelConstants.FILE_NAME, "数据字典");
//		// 注解对象Class
//		mv.addObject(NormalExcelConstants.CLASS, SysDictPage.class);
//		// 自定义表格参数
//		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//		mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("数据字典列表", "导出人:"+user.getRealname(), "数据字典"));
//		// 导出数据列表
//		mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
//		return mv;
//	}

	@RequestMapping(value = "/exportXls")
	@AutoLog(value = "数据字典-导出")
	public void exportXls(SysDict sysDict,HttpServletRequest request,HttpServletResponse response) {
		// Step.1 组装查询条件
		String dictName = sysDict.getDictName();
		String dictCode = sysDict.getDictCode();
		if (StringUtils.isNotBlank(dictName)){
			sysDict.setDictName(null);
		}
		if (StringUtils.isNotBlank(dictCode)){
			sysDict.setDictCode(null);
		}
		QueryWrapper<SysDict> queryWrapper = QueryGenerator.initQueryWrapper(sysDict, request.getParameterMap());
		if (StringUtils.isNotBlank(dictName)){
			queryWrapper.like("dict_name",dictName);
		}
		if (StringUtils.isNotBlank(dictCode)){
			queryWrapper.like("dict_code",dictCode);
		}

		//Step.2 AutoPoi 导出Excel
		ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		List<SysDictPage> pageList = new ArrayList<SysDictPage>();

		List<SysDict> sysDictList = sysDictService.list(queryWrapper);
		for (SysDict dictMain : sysDictList) {
			SysDictPage vo = new SysDictPage();
			BeanUtils.copyProperties(dictMain, vo);
			// 查询机票
			List<SysDictItem> sysDictItemList = sysDictItemService.selectItemsByMainId(dictMain.getId());
			vo.setSysDictItemList(sysDictItemList);
			pageList.add(vo);
		}
		UmpPwdManage zip = umpPwdManageService.getZip();
		String fileName = umpPwdManageService.exportXlsRename("数据字典");
		zipEncryUtils.zipPwd(response, SysDictPage.class,fileName,zip.getZipPwd(),zip.getIsEncry(),pageList);
	}

	@AutoLog(value = "数据字典管理-模板下载")
	@GetMapping(value = "/downloadTemplate")
	@ApiOperation("模板导出")
	public void downloadTemplate(HttpServletResponse response, HttpServletRequest reqsuest) {
		log.info("com.insight.modules.system.controller.SysDictController.downloadTemplate");
		try {
			InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(path);
			String str1 = path.substring(0, path.indexOf('.'));
			String str2 = path.substring(str1.length());
			ExcelUtil.downloadPoi(inputStream, response, "数据字典模板" + str2);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 通过excel导入数据
	 *
	 * @param request
	 * @param
	 * @return
	 */
	//@RequiresRoles({"admin"})
	@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
	public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		if (fileMap == null) {
			return Result.error("文件导入失败！");
		}
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();
			if (file == null || file.isEmpty()) {
				continue;
			}
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(2);
			params.setNeedSave(true);
			params.setSheetNum(1);
			try {
				boolean aBoolean = FieldPresenceUtil.fieldPresence(file.getInputStream(), SysDictPage.class, params, file.getOriginalFilename());
				if (!aBoolean) {
					throw new IllegalArgumentException("导入 Excel 标题格式不匹配，请检查模板是否正确");
				}
				List<SysDictPage> list = ExcelImportUtil.importExcel(file.getInputStream(), SysDictPage.class, params);
				List<String> errorMessage = new ArrayList<>();
				int successLines = 0, errorLines = 0;
				if (list != null) {
					for (int i = 0; i < list.size(); i++) {
						if (list.get(i) == null) {
							errorLines++;
							int lineNumber = i + 1;
							errorMessage.add("第 " + lineNumber + " 行：数据为空，忽略导入。");
							continue;
						}
						SysDict po = new SysDict();
						try {
							BeanUtils.copyProperties(list.get(i), po);
							po.setDelFlag(CommonConstant.DEL_FLAG_0);
							if (sysDictService != null) {
								Integer integer = sysDictService.saveMain(po, list.get(i).getSysDictItemList());
								if (integer > 0) {
									successLines++;
								} else {
									errorLines++;
									int lineNumber = i + 1;
									errorMessage.add("第 " + lineNumber + " 行：字典编码已经存在，忽略导入。");
								}
							} else {
								errorLines++;
								int lineNumber = i + 1;
								errorMessage.add("第 " + lineNumber + " 行：服务不可用，忽略导入。");
							}
						} catch (Exception e) {
							errorLines++;
							int lineNumber = i + 1;
							errorMessage.add("第 " + lineNumber + " 行：字典编码已经存在，忽略导入。");
						}
					}
				}
				return ImportExcelUtil.imporReturnRes(errorLines, successLines, errorMessage);
			} catch (Exception e) {
				log.error(e.getMessage(), e);
				return Result.error("文件导入失败:" + e.getMessage());
			} finally {
				try {
					file.getInputStream().close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return Result.error("文件导入失败！");
	}


	/**
	 * 查询被删除的列表
	 * @return
	 */
	@AutoLog(value = "数据字典-回收站")
	@RequestMapping(value = "/deleteList", method = RequestMethod.GET)
	public Result<List<SysDict>> deleteList() {
		Result<List<SysDict>> result = new Result<List<SysDict>>();
		List<SysDict> list = this.sysDictService.queryDeleteList();
		result.setSuccess(true);
		result.setResult(list);
		return result;
	}

	/**
	 * 物理删除
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/deletePhysic/{id}", method = RequestMethod.DELETE)
	public Result<?> deletePhysic(@PathVariable String id) {
		try {
			if (sysDictService != null && id != null) {
				sysDictService.deleteOneDictPhysically(id);
				return Result.ok("删除成功!");
			}
			return Result.error("删除失败!");
		} catch (Exception e) {
			e.printStackTrace();
			return Result.error("删除失败!");
		}
	}

	/**
	 * 取回
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/back/{id}", method = RequestMethod.PUT)
	public Result<?> back(@PathVariable String id) {
		try {
			if (sysDictService != null && id != null) {
				sysDictService.updateDictDelFlag(0,id);
				return Result.ok("操作成功!");
			}
			return Result.error("操作失败!");
		} catch (Exception e) {
			e.printStackTrace();
			return Result.error("操作失败!");
		}
	}

    /**
     * 根据父id获取行政区划树
     * @param pid 父id
     * @return
     */
    @RequestMapping(value = "/getAreaTree", method = RequestMethod.GET)
	public Result<List<SysAreaTreeModel>> getAreaTree(String pid) {
		log.info(" pid : "+ pid);
		if (StringUtils.isEmpty(pid)) {
			pid = cacheUtils != null ? cacheUtils.getValueByKey(CommonConstant.DATA_DICT_KEY + "project_cityId_id") + "" : "";
		}
		Result<List<SysAreaTreeModel>> result = new Result<List<SysAreaTreeModel>>();
		List<SysAreaTreeModel> ls = null;
		try {
			if (sysDictService != null) {
				ls = sysDictService.queryAreaTreeByPid(pid);
			}
			result.setSuccess(true);
			result.setResult(ls);
			log.info(result.toString());
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			result.error500("操作失败");
			return result;
		}
		return result;
	}

    @RequestMapping(value = "/getSysAreaList", method = RequestMethod.GET)
    public Result<List<SysArea>> getSysAreaList(){
        Result<List<SysArea>> result = new Result<>();
        List<SysArea> sysAreaList = new ArrayList<>();
		sysArea = cacheUtils.getValueByKey(CommonConstant.DATA_DICT_KEY + "project_cityId_id") + "";
        if(!"100000".equals(sysArea)){
            sysAreaList = sysDictService.queryAreaItemsByPid(sysArea);
        }else{
            sysAreaList = sysDictService.querySysAreaAll();
        }

        result.setResult(sysAreaList);
        result.setMessage("操作成功");
        return result;
    }

    @RequestMapping(value = "/getAreaCode", method = RequestMethod.GET)
    public Result<Map<String,String>> getAreaCode(){
        Result<Map<String,String>> result = new Result<>();
		sysArea = cacheUtils.getValueByKey(CommonConstant.DATA_DICT_KEY + "project_cityId_id") + "";
        SysArea sysArea = sysDictService.queryAreaById(this.sysArea);
        Map<String,String> map = new HashMap<>(2);
        map.put("areaId",sysArea.getId());
        map.put("text",sysArea.getText());
        result.setResult(map);
        result.setMessage("操作成功");
        return result;
    }

	@RequestMapping(value = "/getAreaInfo", method = RequestMethod.GET)
	public Result<SysArea> getAreaInfo(String areaId){
		return Result.OK(sysDictService.queryAreaById(areaId));
	}

	/**
	 * 获取sys_dict表下拉数据
	 * @return
	 */
	@GetMapping("/getAllDict")
	public Result<?> getAllDict(){
		List<SysDict> list = sysDictService.list();
		List<JSONObject> resultData = new ArrayList<>();
		for (SysDict sysDict : list) {
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("dictCode",sysDict.getDictCode());
			jsonObject.put("dictName", sysDict.getDictName());
//			jsonObject.put("dictType", sysDict.getType());
			resultData.add(jsonObject);
		}
		return Result.ok(resultData);
	}


}
